package com.senseuni.da.ui

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.elvishew.xlog.XLog
import com.senseuni.da.BuildConfig
import com.senseuni.da.R
import com.senseuni.da.UpgradeActivity
import com.senseuni.da.databinding.FragmentAboutBinding
import com.senseuni.da.db.entity.UpgradeEntity
import com.senseuni.da.http.ApiDataSource
import com.senseuni.da.utils.showToast
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.text.SimpleDateFormat
import java.util.*

class AboutFragment : Fragment() {

    companion object {
        fun newInstance() = AboutFragment()
    }

    private lateinit var binding: FragmentAboutBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentAboutBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.sivCheckUpgrade.setOnClickListener {
            ApiDataSource.instance.checkUpgrade()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : io.reactivex.Observer<UpgradeEntity> {
                    override fun onSubscribe(d: Disposable) {}
                    override fun onNext(entity: UpgradeEntity) {
                        XLog.d("found new version:%s", entity.version)
                        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                        binding.sivCheckUpgrade.setSummary(String.format(getString(R.string.last_check_time), dateFormat.format(Date())))
                        val intent = Intent()
                        intent.setClass(requireContext(), UpgradeActivity::class.java)
                        intent.putExtra("id", entity.id)
                        startActivity(intent)
                    }

                    override fun onError(e: Throwable) {
                        XLog.e("checkUpgrade fail:" + e.message)
                        e.message?.showToast()
                    }

                    override fun onComplete() {}
                })
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        binding.sivHwModel.setSummary(Build.MANUFACTURER + " " + Build.MODEL)
        binding.sivPeerId.setSummary("")
        binding.sivVersion.setSummary("v${BuildConfig.VERSION_NAME }(${BuildConfig.VERSION_CODE})")
    }

}